package cn.itsource.crm.web.fileutil;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.awt.datatransfer.MimeTypeParseException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class FileUploadUtil {

    /**
     * 上传图片
     * @param imageFile 文件对象
     * @param directory 存储目录 如"/upload"
     * @param  fileSize 文件大小 单位为字节
     * @param req
     * @return
     * @throws MimeTypeParseException 文件类型非图片文件时抛出异常
     */
    public static String fileUpload(MultipartFile imageFile, String directory, HttpServletRequest req,Long fileSize) throws Exception {

        ServletContext context = req.getServletContext();
        InputStream in = null;
        FileOutputStream out = null;
        String fileName = null;

        if (!imageFile.isEmpty()) {

                // 判断文件类型
                fileName = imageFile.getOriginalFilename();
                String mimeType = context.getMimeType(fileName);
                if (!(mimeType != null && mimeType.startsWith("image/"))) {
                    throw new MimeTypeParseException("文件类型错误,请上传图片");
                }

                //限制文件大小
                long size = imageFile.getSize();
                if(size>fileSize){
                    throw new MaxUploadSizeExceededException(fileSize);
                }

            try {
                // 输入流
                in = imageFile.getInputStream();

                // 文件名随机处理
                fileName = UUID.randomUUID().toString().replaceAll("-", "") + "_" + fileName;
                // 存储目录路径
                String realPath = context.getRealPath(directory);
                //若目录不存在则创建
                File file2 = new File(realPath);
                if (!file2.exists()) {
                    file2.mkdir();
                }
                // 完整输出路径
                File file = new File(realPath, fileName);

                // 输出
                out = new FileOutputStream(file);
                IOUtils.copy(in, out);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
        return fileName;
    }

    /**
     *判断是否有上传文件,防止没有上传文件时报null异常
     * @param fileName 跟前台传过来的文件对象名一致
     * @param req
     * @return org.springframework.web.multipart.MultipartFile
     * @throws
     * @Description:
     * @author xjh
     * @date
     */
    public static MultipartFile isMultipart(String fileName, HttpServletRequest req) {
        MultipartFile imageFile = null;
        //判断当前请求是否是上传请求
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart) {
            MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(req, MultipartHttpServletRequest.class);
            /*是上传请求则获取该文件,并命名为fileName*/
            imageFile = multipartRequest.getFile(fileName);
        }
        return imageFile;
    }
}
